﻿@{
    ViewBag.Title = "Observable Variable";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div >
    <ol class="breadcrumb">
        <li><a href="/Home/Home">Home</a></li>
        <li><a href="/KnockoutJs/Introduction">KnockOut JS</a></li>
        <li class="active">Observable</li>
    </ol>
    <div id="observable">
        <h1 class="text-left">Observables</h1>
        <p>Knockout is built around three core features:</p>
        <ol start="1" style="padding-left: 25px;">
            <li><p><strong>Observables and dependency tracking: </strong>Observable has holds contain of particular item and using the observable we can do dependency with text or etc.</p></li>
            <li><p><strong>Declarative bindings: </strong>Declaration bindings for binding with value, text, html, css and etc.</p></li>
            <li><p><strong>Templating: </strong>The templating populates the associated DOM element with the results of rendering a template. Templates are a simple and convenient way to build sophisticated UI structures - possibly with repeating or nested blocks - as a function of your view model data.</p></li>
        </ol>
        <p>Previous example we have problems with not hold value that can solve by observable, Observable's holds value of the viewmodel and contain can be change in text but not in viewmodel.</p>
        <div class="divcolor">
            <pre><code>function AppViewModel() {<br />this.firstName = ko.observable('Jack');<br />this.lastName = ko.observable('Reacher');<br />}</code></pre>
        </div>
        <a href="#">Live Demo</a>
    </div>
    <div id="observalescomputed">
        <h1 class="text-left">Computed Observables</h1>
        <p>
            What if you’ve got an observable for firstName, and another for lastName, and you want to display the full name? That’s where computed observables come in - these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change. For example, given the following view model class,
        </p>
        <h3>Example</h3>
        <strong> A Computing Fullname</strong>
        <div class="divcolor">
            <pre>
<code>function AppViewModel(){<br />this.firstName = ko.observable('Jack');<br />this.lastName = ko.observable('Reacher');<br />}</code></pre>
        </div><div>
            <p>
                … you could add a computed observable to return the full name. Computed observable is compute operation of viewmodel variable.
            </p>
        </div>
        <div class="divcolor">
            <pre><code>function AppViewModel() {<br />this.fullName = ko.computed(function() {<br />return this.firstName() + " " + this.lastName();<br />}, this);<br />ko.applyBindings(new AppViewModel());<br />}</code></pre>
        </div>
        <div><p>Now you could bind UI elements to it, using data-bind and display fullname with text bind.</p></div>
        <div class="divcolor">
            <pre><code>The name is &lt;span data-bind="text: fullName"&gt;&lt;/span&gt;
</code></pre>
        </div>
        <a href="">Live Demo</a>
        <h3>Example</h3>
        <strong> A Value Converter</strong>
        <p>
            Sometimes you might want to represent a data point on the screen in a different format from its
            underlying storage. For example, you might want to store a price as a raw float value, but let the user edit
            it with a currency symbol and fixed number of decimal places. You can use a writeable computed
            observable to represent the formatted price, mapping incoming values back to the underlying float value:
        </p>
        <div class="divcolor">
            <pre><code>function MyViewModel() {
this.price = ko.observable(25.99);     
this.formattedPrice = ko.computed({
read: function () {
return '$' + this.price().toFixed(2);
},
ko.applyBindings(new MyViewModel());</code></pre>
        </div>
        <p>It’s trivial to bind the formatted price to a text box:</p>
        <div class="divcolor">
            <pre><code>&lt;p&gt;Enter bid price: &lt;input data-bind="value: formattedPrice" /&gt;&lt;/p&gt;</code></pre>
        </div>
        <p>
            Now, whenever the user enters a new price, the text box immediately updates to show it formatted with
            the currency symbol and two decimal places, no matter what format they entered the value in. This gives
            a great user experience, because the user sees how the software has understood their data entry as a
            price. They know they can’t enter more than two decimal places, because if they try to, the additional
            decimal places are immediately removed. Similarly, they can’t enter negative values, because
            the write callback strips off any minus sign.
        </p>
        <a href="#">Live Demo</a>
    </div>
    <div id="Dependancytracking">
        <h1 class="text-left">Dependency Tracking</h1>
        <p>It’s actually very simple and rather lovely. The tracking algorithm goes like this:</p>
        <ol style="padding-left: 25px;">
            <li>
                <p>
                    Whenever you declare a computed observable, KO immediately invokes its evaluator function to
                    get its initial value.
                </p>
            </li>
            <li>
                <p>
                    While your evaluator function is running, KO keeps a log of any observables (or computed
                    observables) that your evaluator reads the value of
                </p>
            </li>
            <li>
                <p>
                    When your evaluator is finished, KO sets up subscriptions to each of the observables (or
                    computed observables) that you’ve touched. The subscription callback is set to cause your
                    evaluator to run again, looping the whole process back to step 1 (disposing of any old
                    subscriptions that no longer apply).
                </p>

            </li>
            <li><p>KO notifies any subscribers about the new value of your computed observable.</p></li>
        </ol>
        <p>
            So, KO doesn’t just detect your dependencies the first time your evaluator runs - it redetects them every
            time. This means, for example, that your dependencies can vary dynamically: dependency A could
            determine whether you also depend on B or C. Then, you’ll only be re-evaluated when either A or your
            current choice of B or C changes. You don’t have to declare dependencies: they’re inferred at runtime
            from the code’s execution.
        </p>
        <p>
            The other neat trick is that declarative bindings are simply implemented as computed observables. So, if a
            binding reads the value of an observable, that binding becomes dependent on that observable, which
            causes that binding to be re-evaluated if the observable changes.
        </p>

    </div>
    <div class="bottomspace" id="obsevablearray">
        <h1 class="text-left">Observable Arrays</h1>
        <p>If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray. This is useful in many scenarios where you’re displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.</p>
        <h3>Example</h3>
        <pre><code>var myObservableArray = ko.observableArray();  
myObservableArray.push('Some value'); </code></pre>
        <h3>Prepopulating an observableArray</h3>
        <p>If you want your observable array not to start empty, but to contain some initial items, pass those items as an array to the constructor. For example</p>
        <div class="divcolor">
            <pre><code>var anotherObservableArray = ko.observableArray([
    { name: "Jack", type: "Reacher" },
    { name: "Jack", type: "Watson" }
]);</code></pre>
        </div>
        <p>
            Behind the scenes, an observableArray is actually an observable whose value is an array
            (plus,observableArray adds some additional features I'll describe in a moment). So, you can get the
            underlying JavaScript array by invoking the observableArray as a function with no parameters, just like
            any other observable. Then you can read information from that underlying array. For example,
        </p>
        <div class="divcolor">
            <pre><code>alert('The length of the array is ' + myObservableArray().length);
alert('The first element is ' + myObservableArray()[0]);</code></pre>
        </div>
        <p>
            <strong>IndexOf:</strong><br />The indexOf function returns the index of the first array item that equals your parameter. For
            example, myObservableArray.indexOf('Blah') will return the zero-based index of the first array entry that
            equalsBlah, or the value -1 if no matching value was found.
        </p>
        <p>
            <strong>Slice:</strong><br />The slice function is the observableArray equivalent of the native JavaScript slice function (i.e., it returns
            the entries of your array from a given start index up to a given end index).
            CallingmyObservableArray.slice(...) is equivalent to calling the same method on the underlying array
            (i.e.,myObservableArray().slice(...)).
        </p>
        <h3>pop, push, shift, unshift, reverse, sort, splice</h3>
        <p>All of these functions are equivalent to running the native JavaScript array functions on the underlying array, and then notifying listeners about the change:</p>
        <ul>
            <li><code>myObservableArray.push('Some new value')</code> adds a new item to the end of array</li>
            <li><code>myObservableArray.pop()</code> removes the last value from the array and returns it</li>
            <li><code>myObservableArray.unshift('Some new value')</code>inserts a new item at the beginning of the array</li>
            <li><code>myObservableArray.shift()</code> removes the first value from the array and returns it</li>
            <li><code>myObservableArray.reverse()</code> reverses the order of the array</li>
            <li>
                <code>myObservableArray.sort()</code> sorts the array contents.
                <div>
                    <ul>
                        <li>By default, it sorts alphabetically (for strings) or numerically (for numbers).</li>
                        <li>
                            <p>
                                Optionally, you can pass a function to control how the array should be sorted. Your function should accept any two objects from the array and return a negative value if the first argument is smaller, a positive value is the second is smaller, or zero to treat them as equal. For example, to sort an array of 'person' objects by last name, you could write
                                <pre><code>myObservableArray.sort(function(left, right)<br /> { return left.lastName == right.lastName ? 0 :<br /> (left.lastName < right.lastName ? -1 : 1) })</code></pre>
                            </p>
                        </li>
                    </ul>
                </div>
            </li>
            <li><code>myObservableArray.splice()</code> removes and returns a given number of elements starting from a given index. For example,<code> myObservableArray.splice(1, 3)</code> removes three elements starting from index position 1 (i.e., the 2nd, 3rd, and 4th elements) and returns them as an array.</li>
        </ul>

        <strong>remove and removeAll:</strong><br /><br />observableArray adds some more useful methods that aren’t found on JavaScript arrays by default:
        <ul>
            <li>
                <p>
                    myObservableArray.remove(someItem) removes all values that equal someItem and returns
                    them as an array
                </p>
            </li>
            <li>
                <p>
                    myObservableArray.remove(function(item) { return item.age < 18 }) removes all values
                    whose age property is less than 18, and returns them as an array
                </p>
            </li>
            <li>
                <p>
                    myObservableArray.removeAll(['Chad', 132, undefined]) removes all values that equal 'Chad',123,
                    or undefined and returns them as an array
                </p>
            </li>
            <li><p>myObservableArray.removeAll() removes all values and returns them as an array</p></li>
        </ul>

    </div>
    <div id="Managingthis">
        <h1 class="text-left">Managing 'this'</h1>
        <p>
            In case you’re wondering what the second parameter to ko.computed is (the bit where I passed this in the
            preceding code), that defines the value of this when evaluating the computed observable. Without passing
            it in, it would not have been possible to refer to this.firstName() or this.lastName(). Experienced
            JavaScript coders will regard this as obvious, but if you’re still getting to know JavaScript it might seem
            strange. (Languages like C# and Java never expect the programmer to set a value for this, but JavaScript
            does, because its functions themselves aren’t part of any object by default.)
        </p>
        <p>
            There’s a popular convention for avoiding the need to track this altogether: if your viewmodel’s
            constructor copies a reference to this into a different variable (traditionally called self), you can then
            use self throughout your viewmodel and don’t have to worry about it being redefined to refer to something
            else.
        </p>
        <div class="divcolor">
            <pre><code>function AppViewModel() {
var self = this;
self.firstName = ko.observable('Jack');
self.lastName = ko.observable('Reacher'); 
self.fullName = ko.computed(function() {
return self.firstName() + " " + self.lastName(); 
});
}</code></pre>
        </div>
        <p>
            Because self is captured in the function’s closure, it remains available and consistent in any nested
            functions, such as the ko.computed evaluator. This convention is even more useful when it comes to event
            handlers, as you’ll see in many of the
            <a href="#">Live Example</a>
        </p>
    </div>
</div>
